# 导入 Flask 模块
from flask import Flask, render_template, request, redirect, url_for,jsonify

# 创建 Flask 应用实例
app = Flask(__name__)

# 返回简单的 JSON 数据
@app.route('/json')
def return_json():
    data = {
        "name": "Alice",
        "age": 25,
        "city": "New York"
    }
    return jsonify(data)

# 返回列表数据
@app.route('/json/list')
def return_json_list():
    data = [
        {"name": "Alice", "age": 25, "city": "New York"},
        {"name": "Bob", "age": 30, "city": "Los Angeles"},
        {"name": "Charlie", "age": 35, "city": "Chicago"}
    ]
    return jsonify(data)

# 定义路由和视图函数
@app.route('/')
def index():
    """主页视图函数"""
    return 'Hello, Flask!'

@app.route('/greet/<name>')
def greet(name):
    """根据用户输入的名字返回问候语"""
    return f'Hello, {name}!'

@app.route('/form', methods=['GET', 'POST'])
def form():
    """表单提交示例"""
    if request.method == 'POST':
        # 获取表单数据
        username = request.form['username']
        return redirect(url_for('greet', name=username))
    return '''
        <form method="post">
            <label for="username">Username:</label>
            <input type="text" name="username" id="username">
            <input type="submit" value="Submit">
        </form>
        <div style="color:#f00;">Button</div>
    '''

@app.route('/template')
def template():
    """模板渲染示例"""
    # 渲染模板文件
    return render_template('example.html', title='Flask Template Example')

# 启动 Flask 应用
if __name__ == '__main__':
    app.run(debug=True)